import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/base/base_app.dart';
import 'package:flutter_base_widget/code2/second_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

//静态路由配置
void main() => runApp(BaseApp(homeWidget: Exam205HomePage()));

class Exam205HomePage extends StatefulWidget {
  @override
  State<Exam205HomePage> createState() => _Exam205HomePageState();
}

///代码清单 7-1-2
///lib/code7/code701_main_page.dart
class _Exam205HomePageState extends State<Exam205HomePage> {
  int _data = 0;
  @override
  Widget build(BuildContext context) {
    //Scaffold 用来搭建页面的主体结构
    return CountInherited(
      data: _data,
      child: Scaffold(
        //页面的主内容区
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  _data++;
                  setState(() {});
                },
                child: const Text("+"),
              ),
              const SizedBox(width: 40),
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  BPage(),
                  const SizedBox(height: 20),
                  CPage(),
                  const SizedBox(height: 20),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

///代码清单 7-1-3
///lib/code7/code701_main_page.dart
class BPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //获取实例
    CountInherited? countInherited = CountInherited.of(context);
    if (countInherited != null) {
      //获取数据
      return Text("B中获取到数据 ${countInherited.data}");
    }
    return Text("B中未获取到数据");
  }
}

class CPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    CountInherited? countInherited = CountInherited.of(context);
    if (countInherited != null) {
      return Text("C中获取到数据 ${countInherited.data}");
    }
    return Text("C中未获取到数据");
  }
}

///代码清单 7-1-1
///lib/code7/code701_main_page.dart
@immutable
class CountInherited extends InheritedWidget {
  //共享数据
  final int data;
  const CountInherited({Key? key, this.data = 0, required Widget child})
      : super(key: key, child: child);

  //定义一个方法，方便子树中的widget获取这个widget，进而获得共享数据。
  static CountInherited? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<CountInherited>(
        aspect: CountInherited);
  }

  @override
  bool updateShouldNotify(CountInherited oldWidget) {
    return true;
  }
}
